// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const _ = db.command

// 沟通诉求 (与诉求建立链接)
const communicationAndAppeal = async function (params) {
  const wxContext = cloud.getWXContext()
  const handleOpenid = params._openid
  let userIds = [handleOpenid, wxContext.OPENID]

  // 不可与自己沟通
  if (handleOpenid === wxContext.OPENID) {
    console.log('appealSave error 不可与自己沟通哦！')
    return false
  }

  // 如果已经建立链接就直接返回true
  const chats = await db.collection('chat').where({
    userIds: _.all(userIds),
    // delFlag: false,
    // enabled: true
  }).get()
  
  if(chats.data.length>0){
    return chats.data[0]
  }
  





  // 创建建立链接的必要数据
  let appealUsers = await db.collection('user').where({
    _openid: _.in(userIds)
  }).get()
  appealUsers = appealUsers.data


  let data = {
    appealId: params.appealId,
    userIds: userIds,
    chatUser: appealUsers,
    createTime: db.serverDate(),
    updateTime: db.serverDate(),
    type: 2,
  }

  

  try {

    const result = await db.collection('chat').add({
      data: data
    })

    return result

  } catch (error) {

    console.log('appealSave error' + error)

    return false
  }

}

module.exports = communicationAndAppeal